﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CloudReader.Design.Struct
{
    public struct HSV
    {
        public HSV(System.Windows.Media.Color color)
        {
            var R = color.R / 255f;
            var G = color.G / 255f;
            var B = color.B / 255f;
            var max = R > G ? (R > B ? R : B) : (G > B ? G : B);
            var min = R < G ? (R < B ? R : B) : (G < B ? G : B);

            var pl = max - min;
            var ph = max + min;
            if (max == min)
            {
                H = 0;
            }
            else if (max == R && G >= B)
            {
                H = 60 * ((G - B) / pl) + 0;
            }
            else if (max == R && G < B)
            {
                H = 60 * ((G - B) / pl) + 360;
            }
            else if (max == G)
            {
                H = 60 * ((B - R) / pl + 120);
            }
            else
            {
                H = 60 * ((R - G) / pl + 240);
            }

            if (max == 0)
            {
                S = 0f;
            }
            else
            {
                S = pl / max;
            }
            V = max;
        }
        internal System.Windows.Media.Color GetRGB()
        {
            var Hi = H / 60 % 6;
            var f = H / 60 - H;
            var p = V * (1 - S);
            var q = V * (1 - f * S);
            var t = V * (1 - (1 - f) * S);
            var color = new System.Windows.Media.Color();
            switch (Hi)
            {
                case 0:
                    color.R = Convert.ToByte(V);
                    color.G = Convert.ToByte(t);
                    color.B = Convert.ToByte(p);
                    break;
                case 1:
                    color.R = Convert.ToByte(q);
                    color.G = Convert.ToByte(V);
                    color.B = Convert.ToByte(p);
                    break;
                case 2:
                    color.R = Convert.ToByte(p);
                    color.G = Convert.ToByte(V);
                    color.B = Convert.ToByte(t);
                    break;
                case 3:
                    color.R = Convert.ToByte(p);
                    color.G = Convert.ToByte(q);
                    color.B = Convert.ToByte(V);
                    break;
                case 4:
                    color.R = Convert.ToByte(t);
                    color.G = Convert.ToByte(p);
                    color.B = Convert.ToByte(V);
                    break;
                case 5:
                    color.R = Convert.ToByte(V);
                    color.G = Convert.ToByte(p);
                    color.B = Convert.ToByte(q);
                    break;
            }
            return color;
        }
        public float H { get; set; }
        public float S { get; set; }
        public float V { get; set; }
    }
}
